//
//  YMVViewController.m
//  STL_ Animation
//
//  Created by DJtd on 16/4/3.
//  Copyright © 2016年 STL. All rights reserved.
//

#import "YMVViewController.h"

@interface YMVViewController ()<UITableViewDelegate, UITableViewDataSource, bigAction>

@property (nonatomic, strong) STLSliderAndButtons *playView;
@property (nonatomic, strong) UIView *descView;
@property (nonatomic, strong) UISegmentedControl *seg;


@property (nonatomic, strong) UIView *descriptionView;
@property (nonatomic, strong) UITableView *listTableView;
@property (nonatomic, strong) UITableView *commentTableView;

@property (nonatomic, strong) NSMutableArray *dataSourceList;
@property (nonatomic, strong) NSMutableArray *dataSourceComment;
@property (nonatomic, assign) NSInteger pageComment;
@property (nonatomic, assign) BOOL isRequestComment;
//
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *updateLabel;
@property (nonatomic, strong) UILabel *watchTimesLabel;
@property (nonatomic, strong) UILabel *collectTimesLabel;
@property (nonatomic, strong) UILabel *integralLabel;
@property (nonatomic, strong) UILabel *informationLabel;
//

@property (nonatomic, assign) NSInteger cellColor;

@end

@implementation YMVViewController
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //
    //    self.avPlayer = [STLAvPlayer shareAVPlayer];
    //导航栏
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"return"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarAction)];
    self.navigationItem.title = self.homeModel.title;
    [self.navigationController.navigationBar setTitleTextAttributes: @{NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    
    self.cellColor = 0;
    //
    self.dataSourceList = [NSMutableArray arrayWithCapacity:0];
    self.dataSourceComment = [NSMutableArray arrayWithCapacity:0];
    self.pageComment = 0;
    self.NUM = 0;
    self.isRequestComment = NO;
    
    [self creatMVView];
    
    [self creatListView];
    [self creatCommentView];
    [self creatDescriptionView];
    
    
    [self requestYMV];
    [self requestComment];
    
    //    [self creatButtons];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cellColor:) name:@"gg" object:nil];
    
    
    [self.view bringSubviewToFront:self.playView];
    [self.view reloadInputViews];
}
- (void)cellColor:(NSNotification *)sender {
    NSNumber *num = sender.object;
    self.cellColor = num.integerValue;
    [self.listTableView reloadData];
}

- (void)leftBarAction {
    [self.playView.avPlayer pause];
    [self.playView.timer invalidate];
    self.playView.timer = nil;
    [self.playView.timerHidden invalidate];
    self.playView.timerHidden = nil;
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)creatMVPlayingView {
    self.playView = [[STLSliderAndButtons alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight / 3) withIndextPathNUM:self.NUM withType_OneIsYuedan_TwoIsMV:1 withNSMutableArray:self.dataSourceList];
    [self.view addSubview:self.playView];
    self.playView.bigDelegate = self;
}
//网络请求
- (void)requestYMV {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    NSString *url = @"http://mapi.yinyuetai.com/playlist/show.json?D-A=0&id=%@";
    
    [SJAFNetTool GEtNetWithUrl:[NSString stringWithFormat:url, self.homeModel._id] WithBody:nil headerFile:Dictionary response:SJJSON success:^(id result) {
        
        if (result) {
            self.yMvModel = [[YMVBaseModel alloc] initWithDataSource:result];
            
            for (HomePageBaseModel *modle in self.yMvModel.videos  ) {
                
                [self.dataSourceList addObject:modle];
            }
            [self creatMVPlayingView];
            [self.listTableView reloadData];
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
     } failure:^(NSError *error) {
         [MBProgressHUD showAlertView:@"" andMessage:@"网络错误"];
     }];

}
- (void)requestComment {
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    NSString *url = @"http://mapi.yinyuetai.com/playlist/comment/list.json?D-A=0&id=%@&offset=%ld&size=20&v=2";
    //    YMVCommentModel
    [SJAFNetTool GEtNetWithUrl:[NSString stringWithFormat:url, self.homeModel._id, self.pageComment] WithBody:nil headerFile:Dictionary response:SJJSON success:^(id result) {
        
        if (result) {
            if (self.isRequestComment == YES) {
                [self.dataSourceComment removeAllObjects];
                self.isRequestComment = NO;
            }
            
            for (NSDictionary *dic in result[@"comments"]) {
                self.yMvCommentModel = [[YMVCommentModel alloc] init];
                [self.yMvCommentModel setValuesForKeysWithDictionary:dic];
                [self.dataSourceComment addObject:self.yMvCommentModel];
            }
            
            [self.commentTableView reloadData];
//            [MBProgressHUD hideHUDForView:self.view animated:YES];

        }
        
    } failure:^(NSError *error) {
//        [MBProgressHUD showAlertView:@"" andMessage:@"网络错误"];
    }];

}
//刷新
- (void)upRequest {
    self.pageComment = 0;
    self.isRequestComment = YES;
    [self requestComment];
    [self.commentTableView.mj_header endRefreshing];
}
- (void)downRequest {
    self.pageComment += 20;
    [self requestComment];
    [self.commentTableView.mj_footer endRefreshing];
}

//播放页面
- (void)creatMVView {
    //seg
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"悦单描述", @"悦单评论", @"悦单列表"]];
    self.seg.frame = CGRectMake(5, ScreenHeight / 3 + 2, ScreenWidth - 10, ScreenHeight / 20);
    [self.view addSubview:self.seg];
    self.seg.selectedSegmentIndex = 0;
    
    [self.seg addTarget:self action:@selector(segAction) forControlEvents:UIControlEventValueChanged];
    
    [self.seg setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
    
    self.seg.tintColor = [UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1];
    
}

//大屏
- (void)bigOrSmall {
    BigMVViewController *bigVC = [[BigMVViewController alloc] init];
 
    bigVC.ymvModel = self.yMvModel;
    
    [self presentViewController:bigVC animated:YES completion:^{
    }];
}



//seg
- (void)segAction {
    if (self.seg.selectedSegmentIndex == 2) {
        [self.view bringSubviewToFront:self.listTableView];
        
        [self.listTableView reloadData];
        
    }
    if (self.seg.selectedSegmentIndex == 0) {
        [self.view bringSubviewToFront:self.descriptionView];
    }
    if (self.seg.selectedSegmentIndex == 1) {
        [self.view bringSubviewToFront:self.commentTableView];
        [self.commentTableView reloadData];
    }
}

//评论列表
- (void)creatCommentView {
    self.commentTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, ScreenHeight / 3 + self.seg.bounds.size.height + 4, ScreenWidth, ScreenHeight - ScreenHeight / 3 - self.seg.bounds.size.height - 68) style:UITableViewStylePlain];
    [self.view addSubview:self.commentTableView];
    self.commentTableView.delegate = self;
    self.commentTableView.dataSource = self;
    
    self.commentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.commentTableView.showsVerticalScrollIndicator = NO;
    self.commentTableView.backgroundColor = [UIColor blackColor];
    //刷新
    [self.commentTableView setMj_header:[MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(upRequest)]];
    //
    self.commentTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(downRequest)];
    [self.commentTableView registerClass:[YMVCommentTableViewCell class] forCellReuseIdentifier:@"com"];
}

//推荐mv列表
- (void)creatListView {
    self.listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, ScreenHeight / 3 + self.seg.bounds.size.height + 4, ScreenWidth, ScreenHeight - ScreenHeight / 3 - self.seg.bounds.size.height - 68) style:UITableViewStylePlain];
    [self.view addSubview:self.listTableView];
    self.listTableView.delegate = self;
    self.listTableView.dataSource = self;
    self.listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.listTableView.showsVerticalScrollIndicator = NO;
    self.listTableView.backgroundColor = [UIColor blackColor];
    //    YMVListTableViewCell
    [self.listTableView registerClass:[YMVListTableViewCell class] forCellReuseIdentifier:@"list"];
}


//返回tableview
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.listTableView) {
        return ScreenHeight / 8;
    } else {
        YMVCommentTableViewCell *cell = (YMVCommentTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        return [cell cellHeight];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.listTableView) {
        if (self.dataSourceList.count != 0) {
            return self.dataSourceList.count;
        }
    }
    return self.dataSourceComment.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.listTableView) {
        YMVListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.homeModel = self.dataSourceList[indexPath.row];
        if (indexPath.row == self.cellColor) {
            cell.title.textColor = [UIColor redColor];
        } else {
            cell.title.textColor = [UIColor whiteColor];
        }
        return cell;
    }
    YMVCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"com"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.commentModel = self.dataSourceComment[indexPath.row];
    
    return cell;
}
//悦单描述的view
- (void)creatDescriptionView {
    
    self.descriptionView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight / 3 + self.seg.bounds.size.height + 4, ScreenWidth, ScreenHeight - ScreenHeight / 3 - self.seg.bounds.size.height - 4)];
    self.descriptionView.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:self.descriptionView];
    
    //    self.descriptionView.bounds.size.height / 12
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, ScreenWidth - 4, self.descriptionView.bounds.size.height / 12)];
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(2, self.descriptionView.bounds.size.height / 12, ScreenWidth / 2, self.descriptionView.bounds.size.height / 12)];
    self.updateLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth / 2, self.descriptionView.bounds.size.height / 12, ScreenWidth / 2, self.descriptionView.bounds.size.height / 12)];
    self.watchTimesLabel = [[UILabel alloc] initWithFrame:CGRectMake(2, self.descriptionView.bounds.size.height / 6, ScreenWidth / 3, self.descriptionView.bounds.size.height / 12)];
    self.collectTimesLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth / 3, self.descriptionView.bounds.size.height / 6, ScreenWidth / 3, self.descriptionView.bounds.size.height / 12)];
    self.integralLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth / 3 * 2, self.descriptionView.bounds.size.height / 6, ScreenWidth / 3, self.descriptionView.bounds.size.height / 12)];
    //为了自适应
    self.informationLabel = [[UILabel alloc] init];
    self.informationLabel.font = [UIFont systemFontOfSize:12];
    self.informationLabel.numberOfLines = 0;
    
    
    [self.descriptionView addSubview:self.titleLabel];
    [self.descriptionView addSubview:self.nameLabel];
    [self.descriptionView addSubview:self.updateLabel];
    [self.descriptionView addSubview:self.watchTimesLabel];
    [self.descriptionView addSubview:self.collectTimesLabel];
    [self.descriptionView addSubview:self.integralLabel];
    [self.descriptionView addSubview:self.informationLabel];
    
    self.nameLabel.textColor = [UIColor lightGrayColor];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.updateLabel.textColor = [UIColor lightGrayColor];
    self.watchTimesLabel.textColor = [UIColor lightGrayColor];
    self.collectTimesLabel.textColor = [UIColor lightGrayColor];
    self.integralLabel.textColor = [UIColor lightGrayColor];
    self.informationLabel.textColor = [UIColor whiteColor];
    
    self.nameLabel.font = [UIFont systemFontOfSize:12];
    self.titleLabel.font = [UIFont systemFontOfSize:14];
    self.updateLabel.font = [UIFont systemFontOfSize:12];
    self.watchTimesLabel.font = [UIFont systemFontOfSize:12];
    self.collectTimesLabel.font = [UIFont systemFontOfSize:12];
    self.integralLabel.font = [UIFont systemFontOfSize:12];
    
}


//setmodel
- (void)setYMvModel:(YMVBaseModel *)yMvModel {
    _yMvModel = yMvModel;
    self.titleLabel.text = [NSString stringWithFormat:@" %@", yMvModel.title];
    NSString *nameStr = [NSString stringWithFormat:@" 作者:%@", yMvModel.creatorModel.nickName];
    NSString *updateStr = [NSString stringWithFormat:@"更新时间:%@", yMvModel.updateTime];
    NSString *watchTimesStr = [NSString stringWithFormat:@" 播放次数:%@", yMvModel.totalViews];
    NSString *collecTimesStr = [NSString stringWithFormat:@"收藏:%@", yMvModel.totalFavorites];
    NSString *integralStr = [NSString stringWithFormat:@"获得积分:%@", yMvModel.integral];
    self.informationLabel.text = [NSString stringWithFormat:@"%@", yMvModel.descriptionModel];
    //frame要写在赋完text之后
    self.informationLabel.frame = CGRectMake(5, self.descriptionView.bounds.size.height / 4, ScreenWidth - 10, [self heightWithFont:self.informationLabel.font withText:self.informationLabel.text]);
    //范围
    NSRange nameRange = [nameStr rangeOfString:[NSString stringWithFormat:@"%@", yMvModel.creatorModel.nickName]];
    NSRange updateRange = [updateStr rangeOfString:[NSString stringWithFormat:@"%@", yMvModel.updateTime]];
    NSRange watchTimesRange = [watchTimesStr rangeOfString:[NSString stringWithFormat:@"%@", yMvModel.totalViews]];
    NSRange collecTimesRange = [collecTimesStr rangeOfString:[NSString stringWithFormat:@"%@", yMvModel.totalFavorites]];
    NSRange integralRange = [integralStr rangeOfString:[NSString stringWithFormat:@"%@", yMvModel.integral]];
    
    //
    NSMutableAttributedString *nameAttStr = [[NSMutableAttributedString alloc] initWithString:nameStr];
    NSMutableAttributedString *updateAttStr = [[NSMutableAttributedString alloc] initWithString:updateStr];
    NSMutableAttributedString *watchAttStr = [[NSMutableAttributedString alloc] initWithString:watchTimesStr];
    NSMutableAttributedString *collectAttStr = [[NSMutableAttributedString alloc] initWithString:collecTimesStr];
    NSMutableAttributedString *integralAttStr = [[NSMutableAttributedString alloc] initWithString:integralStr];
    //改变的值
    [nameAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1] range:nameRange];
    [updateAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:updateRange];
    [watchAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:watchTimesRange];
    [collectAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:collecTimesRange];
    [integralAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:integralRange];
    
    
    
    self.nameLabel.attributedText = nameAttStr;
    self.updateLabel.attributedText = updateAttStr;
    self.watchTimesLabel.attributedText = watchAttStr;
    self.collectTimesLabel.attributedText = collectAttStr;
    self.integralLabel.attributedText = integralAttStr;
}

//label自适应
- (CGFloat)heightWithFont:(UIFont *)font withText:(NSString *)text {
    // 字体以及大小
    NSDictionary *fontDic = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    // 计算宽高
    CGSize size = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:fontDic context:nil].size;
    // 返回计算完成的高度
    return size.height + 1;
}



//点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    
    if (tableView == self.listTableView) {
        self.NUM = indexPath.row;
        NSLog(@"---点击了列表的第%ld首mv---", self.NUM);
        
        
        [self.playView removeFromSuperview];
        
        
        self.playView = [[STLSliderAndButtons alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight / 3) withIndextPathNUM:self.NUM withType_OneIsYuedan_TwoIsMV:1 withNSMutableArray:self.dataSourceList];
        
        [self.view addSubview:self.playView];
        

        self.playView.bigDelegate = self;
    }
    
    
    
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end




